use std::sync::Arc;

use crate::transport::ice::{create_accept_channel, create_follower_channel};

use super::{IceDialMessage, IceDialResponseMessage, IceMessage};

pub async fn on_message(
    peer_id: &String,
    message: &IceMessage,
    request_id: Option<u64>,
) -> anyhow::Result<Option<String>> {
    //
    match message {
        IceMessage::Dial(msg) => _dial(peer_id, msg, request_id).await,
        IceMessage::DialResponse(msg) => _dial_response(peer_id, msg, request_id).await,
        _ => {
            tracing::debug!("");
            Ok(None)
        }
    }
}

async fn _dial(
    peer_id: &String,
    message: &IceDialMessage,
    request_id: Option<u64>,
) -> anyhow::Result<Option<String>> {
    //创建连接
    let remote_candidates = &message.candidates;
    let remote_pwd = &message.pwd;
    let remote_ufrag = &message.ufrag;

    if let Err(err) = create_accept_channel(
        peer_id,
        remote_ufrag,
        remote_pwd,
        remote_candidates,
        request_id,
    )
    .await
    {
        //
        Ok(Some(serde_json::to_string(&serde_json::json!({
            "type": "relay",
            "data": {
                "type": "unicastResponse",
                "data": {
                    "peer_id": peer_id,
                    "data": {
                        "type": "ice",
                        "data": {
                            "type": "dial_response",
                            "err": format!("{}",err)
                        }
                    }
                }
            },
            "request_id": request_id
        }))?))
    } else {
        Ok(None)
    }
}

pub async fn dial_response(
    peer_id: &String,
    message: &IceDialResponseMessage,
    request_id: Option<u64>,
) -> anyhow::Result<Option<String>> {
    //创建连接
    let remote_candidates = &message.candidates;
    let remote_pwd = &message.pwd;
    let remote_ufrag = &message.ufrag;

    let arc = create_follower_channel(
        peer_id,
        remote_ufrag,
        remote_pwd,
        remote_candidates,
        request_id,
    )
    .await?;
    //返回
    Ok(None)
}

async fn _dial_response(
    peer_id: &String,
    message: &IceDialResponseMessage,
    request_id: Option<u64>,
) -> anyhow::Result<Option<String>> {
    //创建连接
    let remote_candidates = &message.candidates;
    let remote_pwd = &message.pwd;
    let remote_ufrag = &message.ufrag;

    let arc = create_follower_channel(
        peer_id,
        remote_ufrag,
        remote_pwd,
        remote_candidates,
        request_id,
    )
    .await?;
    //返回
    Ok(None)
}
